import {messages, getQueryUrlParam} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Affix, message, Button, Modal, Icon } from 'antd'
import menuRoute from 'routes/menuRoute'
import ApproveExpenseReportService from 'containers/approve/expense-report/approve-expense-report.service'
import ApproveBar from 'components/template/approve-bar'
import financeAuditService from "containers/financial-management/finance-audit/finance-audit.service";
import baseService from "share/base.service";
import expenseReportService from "containers/expense-report/expense-report.service";
import adminApproveListService from 'containers/setting/process-monitoring-platform/admin-approve-list.service'
import approveService from 'containers/approve/approve.service';

class ApproveExpenseReportDetail extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      passLoading: false,
      rejectLoading: false,
      noticeLoading: false,
      printLoading: false,
      checkLoading: false,
      showAdditional: false,
      invoiceNumber: 0, //需查验的发票数量  === failedInvoices.length
      failedInvoices: [], //需查验的发票数组信息，包括未查验的和查验失败的
      companyOIDs: [], //加签人列表
      info: {},
      hangUpLoading: false
    }
  }

  componentWillReceiveProps(nextProps) {
    const { info } = this.state;
    if (nextProps.info.expenseReportOID && nextProps.info.expenseReportOID !== info.expenseReportOID) {
      this.setState({
        info: nextProps.info,
        failedInvoices: nextProps.failedInvoices,
        invoiceNumber: nextProps.failedInvoices.length
      });
      //判断是否可以加签
      if (~location.search.indexOf('approvePending')) {
        ApproveExpenseReportService.isCounterSignEnable(
          this.props.company.companyOID,
          nextProps.info.formOID,
          'enableAddSign',
          getQueryUrlParam('approverOID'),
          nextProps.info.expenseReportOID,
          1002
        ).then(res => {
          this.setState({
            showAdditional: res.data.enabled,
            companyOIDs: res.data.approvalAddSignScope.companyOIDs
          })
        })
      }
    }
  }

  //返回
  goBack = () => {
    menuRoute.goBack(this)
  };

  hasRepeatApproveTip = (value, event, additionalItems) => {
    const { approvalHistory } = this.props;
    let additionalOIDs = [];
    let additionalHaveApprovedNames = [];  //加签人中已审批的用户名
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID)
    });
    let ids = [];
    event.map(item => {
      ids.push(item.id);
    });
    let preApproveOIDs = [];
    approvalHistory.map(item => {
      item.operation === 2001 && (preApproveOIDs.push(item.operatorOID))
    });
    additionalOIDs.map((OID, index) => {
      if (preApproveOIDs.indexOf(OID) > -1) {
        additionalHaveApprovedNames.push(additionalItems[index].fullName)
      }
    });
    if (additionalHaveApprovedNames.length) {
      Modal.confirm({
        title: `${additionalHaveApprovedNames.join('、')} ${messages('approve.key58'/*已经审批通过，是否继续*/)}？`,
        onOk: () => this.handleApprovePass(value, additionalOIDs, ids)
      });
    } else {
      this.handleApprovePass(value, additionalOIDs, ids)
    }
  };

  //审批通过
  handleApprovePass = (value, additionalOIDs, ids) => {
    const { info } = this.props;
    let params = {
      approvalTxt: value,
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: info.expenseReportOID,
        entityType: 1002,
        countersignApproverOIDs: additionalOIDs
      }],
      conditionIds: ids
    };
    let handleService = info.admin ?
      adminApproveListService.handleRequestApprovePass :
      ApproveExpenseReportService.handleExpenseReportApprovePass;
    this.setState({ passLoading: true });
    handleService(params).then(res => {
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success'));
        this.setState({ passLoading: false });
        this.goBack()
      } else {
        this.setState({ passLoading: false });
        message.error(`${messages('common.operate.filed')}，${res.data.failReason[info.expenseReportOID]}`)
      }
    }).catch(e => {
      this.setState({ passLoading: false });
      message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`)
    })
  };

  //审批驳回
  handleApproveReject = (value, event, additionalItems, direct) => {
    let additionalOIDs = [];
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID)
    });
    let ids = [];
    event.map(item => {
      ids.push(item.id);
    });
    const { info, selectedExpense, expenseReportInvoices } = this.props;
    let params = {
      approvalTxt: value,
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: info.expenseReportOID,
        entityType: 1002,
      }],
      conditionIds: ids
    };
    this.setState({ rejectLoading: true });
    additionalOIDs && (params.entities[0].countersignApproverOIDs = additionalOIDs);
    if(selectedExpense.length > 0 && !direct){
      params = {
        approvalTxt: value,
        expenseOID: info.expenseReportOID,
        invoiceOIDs: selectedExpense
      };
      let allReject = true;
      expenseReportInvoices.map(invoice => {
        allReject = allReject && (selectedExpense.indexOf(invoice.invoiceOID) > -1 || invoice.status === 1002);
      });
      if(allReject){
        Modal.confirm({
          content: messages('approve.key59'/*驳回所有费用将直接驳回报销单，你确定驳回吗？*/),
          onOk: () => {
            this.handleService(info.admin ?
              adminApproveListService.handleRequestApproveReject :
              ApproveExpenseReportService.batchRejectInvoice, params, true);
          },
          onCancel: () => {
            this.setState({rejectLoading: false});
          }
        });
      } else {
        this.handleService(info.admin ?
          adminApproveListService.handleRequestApproveReject :
          ApproveExpenseReportService.batchRejectInvoice, params, false);
      }
    } else {
      this.handleService(info.admin ?
        adminApproveListService.handleRequestApproveReject :
        ApproveExpenseReportService.handleExpenseReportApproveReject, params, true, true);
    }
  };

  handleService = (service, params, goBack, isHandleService = false) => {
    const { info, emitRefresh } = this.props;
    service(params).then(res => {
      if (res.status === 200) {
        const { failNum, failReason } = res.data;
        if(isHandleService && failNum !== 0) {
          message.error(`${messages('common.operate.filed')}，${failReason[info.expenseReportOID]}`)
        }else {
          message.success(messages('common.operate.success')/*操作成功*/);
        }
        this.setState({ rejectLoading: false });
        if(goBack){
          this.goBack();
        } else {
          emitRefresh();
        }
      }
    }).catch(e => {
      this.setState({ rejectLoading: false });
      message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`)
    })
  };

  //通知
  handleAuditNotice = (value) => {
    const { info } = this.props;
    let params = {
      entityOID:info.expenseReportOID,
      entityType:1002,
      notice: value
    };
    this.setState({ noticeLoading: true });
    financeAuditService.noticeApplication(params).then(res => {
      if (res.status === 200) {
        message.success(messages("common.operate.success")/*操作成功*/);
        this.setState({ noticeLoading: false });
        this.goBack()
      }
    }).catch(e => {
      this.setState({ noticeLoading: false });
      // message.error(messages("common.operate.filed")/*操作失败*/)
      message.error(e.response.data.message)
    })
  };

  //打印
  handlePrint = () => {
    const { info } = this.props;
    this.setState({printLoading: true});
    baseService.printExpense(info.expenseReportOID).then(res => {
      this.setState({printLoading: false});
      window.open(res.data.link, "_blank")
    });
  };

  //审核查验
  handleAuditCheck = () => {
    const invoice = this.state.failedInvoices;
    this.setState({ checkLoading: true });
    expenseReportService.recheckInvoice(invoice).then(res => {
      if (res.data.failedCount === 0) {
        this.setState({invoiceNumber: 0, failedInvoices: []});
        message.success(messages('approve.key60'/*发票查验成功*/));
      } else {
        this.setState({invoiceNumber: res.data.failedCount, failedInvoices: res.data.failedList});
        message.warn(messages('approve.key61'/*有查验失败的发票信息*/));
      };
      if (res.data.successList.length > 0) {
        this.props.afterClose(true);
      }
      this.setState({ checkLoading: false });
    });
  };

  afterClose = res => {
    res === 'success' && window.history.go(-1);
    // window.history.go(-1);
  };

  /**
   * @desc 暂挂
   */
  handleApproveHangUp = () => {
    const { info } = this.props;
    let params = {
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: info.expenseReportOID,
        entityType: 1002,
      }]
    };
    this.setState({ hangUpLoading: true });
    approveService.handleEntityHangUp(params)
      .then(res => {
        const { failNum, failReason } = res.data;
        if (failNum === 0) {
          message.success(messages('common.operate.success'));
          this.goBack();
        } else {
          message.error(
            `${messages('common.operate.filed')}，${failReason[this.state.info.applicationOID]}`
          );
        }
      })
      .catch(e => {
        message.error(`${messages('common.operate.filed')}，${e.response.data.message}`);
      })
      .finally(() => {
        this.setState({ hangUpLoading: false });
      });
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { approvalChains } = this.props;
    let showHangUp = false;
    let approverOID = getQueryUrlParam('approverOID');
    approvalChains && approvalChains.map(chain => {
      if(chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  allButtons = () => {
    const { selectedExpense, info, isAuditInApproveStatus } = this.props;
    if(selectedExpense.length > 0) return ['reject'];
    if(getQueryUrlParam('approvalMode') !== '1005' && info.admin) return ['reject','pass'];
    if(isAuditInApproveStatus) return ['pass', 'reject', 'notice', 'print', 'skip', 'press']; //审核节点不让管理员转交，warn：和更多操作里的转交不是一个
    //这里返回undefined是为了取approveBars的buttons属性的defaultProps.......
    return undefined;
  };

  render() {
    const {
      passLoading, rejectLoading,
      showAdditional, noticeLoading, printLoading, checkLoading,
      invoiceNumber, companyOIDs, hangUpLoading
    } = this.state;
    const { profile, showApproveBottom, approvalChains, invoiceEnabled, selectedExpense,
      customFormPropertyMap, info } = this.props;
    let moreButtons = [];
    !this.isShowHangUp() && moreButtons.push('hangUp'); //已挂起单据不展示暂挂
    showAdditional && moreButtons.push('additional');
    invoiceNumber > 0 && invoiceEnabled && moreButtons.push('auditCheck');
    customFormPropertyMap && customFormPropertyMap['approvalIsDeliver'] === 'true' && moreButtons.push('approveTransfer');
    let approvalChainsOID = [];
    if (approvalChains && approvalChains.length > 0) {
      approvalChains.map(item => {
        approvalChainsOID.push(item.approverOID)
      })
    }
    if(info.admin) {
      moreButtons = [];
    }
    return (
      ~approvalChainsOID.indexOf(getQueryUrlParam('approverOID')) &&
      showApproveBottom &&
      info.status === 1002 &&
      getQueryUrlParam('approvePending') === 'true' &&
      !profile['er.opt.approval.disabled'] &&
      !profile['er.disabled']
    ) ? (
      <Affix offsetBottom={0} className="bottom-bar bottom-bar-approve">
        <ApproveBar
          goBack={this.goBack}
          moreButtons={moreButtons}
          signCompanyOIDs={companyOIDs}
          customFormPropertyMap={customFormPropertyMap}
          handleApprovePass={this.hasRepeatApproveTip}
          handleApproveReject={this.handleApproveReject}
          handleAuditNotice={this.handleAuditNotice}
          handleAuditPrint={this.handlePrint}
          handleAuditCheck={this.handleAuditCheck}
          handleApproveSkip={this.afterClose}
          handleApproveHangUp={this.handleApproveHangUp}
          handleApproveTransfer={this.goBack}
          handleApproveAdditional={this.goBack}
          needHonest
          applicantOID={info.applicantOID}
          allLoading={passLoading || rejectLoading || noticeLoading || printLoading || checkLoading || hangUpLoading}
          invoiceNumber={invoiceNumber}
          batchNumber={selectedExpense.length}
          btnShowMode="all"
          jobId={info.applicantJobId}
          admin={info.admin}
          isPrint={info.printableByApprover}
          entities={{
            approverOID:getQueryUrlParam('approverOID'),
            entityOID: info.expenseReportOID,
            entityType: 1002,
            applicantOID: info.applicantOID,
            businessCode: info.businessCode,
            formOID: info.formOID
          }}
          buttons={this.allButtons()}
        />
      </Affix>
    ) : (
      <Affix offsetBottom={0} className="bottom-bar">
        {info.printableByApprover && <Button
          loading={printLoading}
          type="primary"
          className="notice-btn"
          onClick={this.handlePrint}
        >
          {messages('common.print')}
        </Button>}
        <a className="back-btn" onClick={this.goBack}>
          <Icon type="rollback"/>
          {messages("common.back")/*返回*/}
        </a>
      </Affix>
    )
  }
}

ApproveExpenseReportDetail.propTypes = {
  info: React.PropTypes.object,
  selectedExpense: React.PropTypes.array,
  expenseReportInvoices: React.PropTypes.array,
  approvalChains: React.PropTypes.array,
  approvalHistory: React.PropTypes.array,
  emitRefresh: React.PropTypes.func,
  showApproveBottom: React.PropTypes.bool,
  auditCapability: React.PropTypes.bool//具体审核能力，因审批流复杂性，让部分审批的单子具备审核能力
};

ApproveExpenseReportDetail.defaultProps={
  info: {},
  selectedExpense: [],
  showApproveBottom: false,
  auditCapability: false
};

ApproveExpenseReportDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(ApproveExpenseReportDetail)
